<?php
/**
 * 产品外链类型
 *
 * @author Lyun
 * @date 2018/6/7
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Panx;

use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * @property-write string $url - 外链商品的 url
 * @property-write string $const
 * @property-write null|string convert_url - 计算转化率的商品跳转链接
 *
 * @mixin Builder
 */
class ProductUrlType extends Model
{
    use Bosable;

    protected static $all_cache;

    protected $table = 'product_url_types';

    protected $guarded = [];

    const ID_NO = 0;
    const ID_TAOBAO = 1;    // 淘宝
    const ID_TMALL = 2;     // 天猫
    const ID_JD = 3;        // 京东
    const ID_VIP = 4;       // 唯品会
    const ID_WECHAT = 5;    // 微信商城
    const ID_AMAZON = 6;    // 亚马逊
    const ID_JUMEI = 7;     // 聚美优品
    const ID_PINDUODUO = 8; // 拼多多
    const ID_SUNING = 9;    // 苏宁易购
    const ID_MOGUJIE = 10;  // 蘑菇街
    const ID_OTHER = 11;  // 其他
    const ID_YOUZAN = 12;  // 有赞
    const ID_MORESHOW = 13;  // 魔售

    /**
     * @deprecated URL_REGEX_MAP
     */
    const URL_REGEX_MAP = [
        self::ID_TAOBAO    => 'regex:/(\.taobao\.).*?\?(.*?&)?id=\d+/',
        self::ID_TMALL     => 'regex:/(\.tmall\.).*?\?(.*?&)?id=\d+/',
        self::ID_JD        => 'regex:/(item\.jd\.com)\/\d+\.html/',
        self::ID_VIP       => 'regex:/(detail\.vip\.com)\/detail\-\d+\-\d+\.html/',
        self::ID_WECHAT    => 'regex:/\.*?/',
        self::ID_AMAZON    => 'regex:/(\.amazon\.)\.*?/',
        self::ID_JUMEI     => 'regex:/(\.jumei\.)\.*?/',
        self::ID_PINDUODUO => 'regex:/(\.yangkeduo\.)\.*?/',
        self::ID_SUNING    => 'regex:/(\.suning\.)\.*?/',
        self::ID_MOGUJIE   => 'regex:/(\.mogujie\.)\.*?/',
    ];

    const PRODUCT_TYPE_IDS = [
        self::ID_NO, self::ID_TAOBAO, self::ID_TMALL,
        self::ID_JD, self::ID_VIP, self::ID_WECHAT,
        self::ID_AMAZON, self::ID_JUMEI, self::ID_PINDUODUO,
        self::ID_SUNING, self::ID_MOGUJIE, self::ID_OTHER, self::ID_YOUZAN
    ];

    /**
     * @return null|string
     */
    public function getTypeIconAttribute()
    {
        if (! $this->attributes['type_icon']) return null;

        return $this->getStaticUrl($this->attributes['type_icon']);
    }

    /**
     * @return null|string
     */
    public function getQrcodeIconAttribute()
    {
        if (! $this->attributes['qrcode_icon']) return null;

        return $this->getStaticUrl($this->attributes['qrcode_icon']);
    }

    /**
     * @param int $id
     * @return string|null
     */
    public static function findFromAllCache(int $id)
    {
        if (! self::$all_cache) {
            self::$all_cache = self::all();
        };

        return self::$all_cache->find($id);
    }

    public function getNameAttribute()
    {
       if(  str_contains(config('app.locale'),'en') )
       {
           return  $this->attributes['name'] = $this->const;
       }

       return $this->attributes['name'];
    }
}
